package cn.lili.modules.grab.dingdong.facade;

import cn.lili.common.event.TransactionCommitSendMQEvent;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.utils.UuidUtils;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.goods.entity.dos.Goods;
import cn.lili.modules.goods.entity.dos.GoodsGallery;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.entity.dos.StoreGoodsLabel;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsMarketEnum;
import cn.lili.modules.goods.service.GoodsGalleryService;
import cn.lili.modules.goods.service.GoodsService;
import cn.lili.modules.goods.service.GoodsSkuService;
import cn.lili.modules.goods.service.StoreGoodsLabelService;
import cn.lili.modules.grab.dingdong.reps.goods.DetailRespose;
import cn.lili.modules.grab.dingdong.reps.goods.GoodsCateRespose;
import cn.lili.modules.grab.dingdong.reps.goods.GoodsQueryRespose;
import cn.lili.modules.grab.dingdong.res.goods.DetailRequest;
import cn.lili.modules.grab.dingdong.res.goods.GoodsQueryRequest;
import cn.lili.modules.grab.enums.SourceEnums;
import cn.lili.routing.GoodsRoutingKey;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
@Slf4j
public class GrabDingdongGoodsFacade {

    @Resource
    private StoreGoodsLabelService storeGoodsLabelService;
    @Resource
    private GoodsSkuService goodsSkuService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private GoodsGalleryService goodsGalleryService;
    @Resource
    private AmqpExchangeProperties amqpExchangeProperties;
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 初始化商品分类并入库
     *
     * @param storeId          店铺ID
     * @param goodsCateRespose 分类数据
     */
    public void storeGoodsLabelInit(String storeId, GoodsCateRespose goodsCateRespose) {
        //查询分类ID是否存在
        LambdaQueryWrapper<StoreGoodsLabel> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(StoreGoodsLabel::getStoreId, storeId);
        queryWrapper1.eq(StoreGoodsLabel::getSourceId, goodsCateRespose.getCate_id());
        queryWrapper1.last("limit 1");
        StoreGoodsLabel storeGoodsLabel1 = storeGoodsLabelService.getBaseMapper().selectOne(queryWrapper1);

        //查询parentId是否存在
        LambdaQueryWrapper<StoreGoodsLabel> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(StoreGoodsLabel::getStoreId, storeId);
        queryWrapper2.eq(StoreGoodsLabel::getSourceId, goodsCateRespose.getParent_id());
        queryWrapper2.last("limit 1");
        StoreGoodsLabel storeGoodsLabel2 = storeGoodsLabelService.getBaseMapper().selectOne(queryWrapper2);

        //更新或新增分类
        if (storeGoodsLabel1 != null) {
            //修改更新
            storeGoodsLabel1.setStoreId(storeId);
            storeGoodsLabel1.setLabelName(goodsCateRespose.getCate_name());
            storeGoodsLabel1.setSortOrder(BigDecimal.valueOf(0));
            storeGoodsLabel1.setParentId(storeGoodsLabel2 != null ? storeGoodsLabel2.getId() : goodsCateRespose.getParent_id());
            storeGoodsLabel1.setLevel(Integer.parseInt(goodsCateRespose.getLevel()) - 1);
            storeGoodsLabel1.setSource(SourceEnums.DINGDONG_GOODS.name());
            storeGoodsLabel1.setSourceId(goodsCateRespose.getCate_id());
            storeGoodsLabelService.editStoreGoodsLabel(storeGoodsLabel1);
        } else {
            //新增
            StoreGoodsLabel storeGoodsLabel = StoreGoodsLabel.builder()
                    .storeId(storeId)
                    .labelName(goodsCateRespose.getCate_name())
                    .sortOrder(BigDecimal.valueOf(0))
                    .parentId(storeGoodsLabel2 != null ? storeGoodsLabel2.getId() : goodsCateRespose.getParent_id())
                    .level(Integer.parseInt(goodsCateRespose.getLevel()) - 1)
                    .source(SourceEnums.DINGDONG_GOODS.name())
                    .sourceId(goodsCateRespose.getCate_id())
                    .build();
            storeGoodsLabelService.addStoreGoodsLabel(storeGoodsLabel);
        }
    }

    /**
     * 根据来源ID查询分类ID
     * @param sourceId 来源ID
     * */
    public String getStoreGoodsLabel(String sourceId){
        if (StringUtils.isEmpty(sourceId)){
            return null;
        }
        LambdaQueryWrapper<StoreGoodsLabel> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(StoreGoodsLabel::getSourceId,sourceId);
        queryWrapper1.last("limit 1");
        StoreGoodsLabel storeGoodsLabel = storeGoodsLabelService.getBaseMapper().selectOne(queryWrapper1);
        return storeGoodsLabel!=null?storeGoodsLabel.getId():null;
    }

    /**
     * 初始化商品并入库
     *
     * @param storeId           店铺ID
     * @param goodsQueryRespose 查询条件
     */
    public void goodsInit(String storeId, GoodsQueryRespose goodsQueryRespose, DetailRespose detailRespose) {
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getStoreId,storeId);
        queryWrapper.eq(Goods::getThirdPartyPlatformId,goodsQueryRespose.getGoods_id());
        queryWrapper.last("limit 1");
        Goods tempGoods = goodsService.getBaseMapper().selectOne(queryWrapper);


        Goods goods = new Goods();
        goods.setGoodsName("DD-" + goodsQueryRespose.getGoods_name());
        goods.setPrice(CurrencyUtil.mul(CurrencyUtil.convertDouble(goodsQueryRespose.getPrice()),1.05,1));
        goods.setDefaultSkuGreenScore(new BigDecimal(CurrencyUtil.mul(CurrencyUtil.convertDouble(goodsQueryRespose.getPrice()),0.1,0)));

        //查询分类
        String cate1 = getStoreGoodsLabel(detailRespose.getGoods().getCate_id_1());
        String cate2 = getStoreGoodsLabel(detailRespose.getGoods().getCate_id_2());
        String cate3 = getStoreGoodsLabel(detailRespose.getGoods().getCate_id_2());


        StringBuffer cateStorePath = new StringBuffer()
                .append(cate1)
                .append(",")
                .append(cate2)
                .append(",")
                .append(cate3);

        //goods.setCategoryPath(catePath.toString());
        goods.setGoodsUnit("件");
        goods.setMarketEnable("DOWN");
        goods.setBuyCount(0);
        goods.setQuantity(Integer.parseInt(detailRespose.getGoods().getStock()));
        goods.setThumbnail(goodsQueryRespose.getDefault_image());
        goods.setSmall(goodsQueryRespose.getDefault_image());
        goods.setOriginal(goodsQueryRespose.getDefault_image());
        goods.setStoreCategoryPath(detailRespose.getGoods().getCate_id_2());
        goods.setStoreId(storeId);
        goods.setStoreName("供应");
        goods.setTemplateId("0");
        goods.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name());
        goods.setSelfOperated(true);
        goods.setRecommend(true);
        goods.setSalesModel("RETAIL");
        goods.setGoodsType("PHYSICAL_GOODS");
        goods.setIsGreenGoods(false);
        goods.setIntro(detailRespose.getGoods().getDescription());
        goods.setMobileIntro(detailRespose.getGoods().getDescription());
        goods.setScene("STORE");
        goods.setExtendId(storeId);
        goods.setThirdPartyPlatformId(goodsQueryRespose.getGoods_id());
        goods.setThirdPartyPlatformType(2);

        //插入商品
        if(tempGoods == null){
            goods.setCategoryPath("1,1,1");
            goodsService.save(goods);
        }else{
            goods.setId(tempGoods.getId());
            BeanUtils.copyProperties(goods,tempGoods);
            goodsService.updateGoods(tempGoods);
        }

        //插入商品相册，删除后新增
        goodsGalleryService.removeByGoodsId(goods.getId());
        for (DetailRespose.Images images:detailRespose.getImages()) {
            GoodsGallery goodsGallery = new GoodsGallery();
            goodsGallery.setGoodsId(goods.getId());
            goodsGallery.setIsDefault(0);
            goodsGallery.setOriginal(images.getImage_url());
            goodsGallery.setThumbnail(images.getImage_url());
            goodsGallery.setSmall(images.getImage_url());
            goodsGalleryService.save(goodsGallery);
        }

        //插入sku
        goodsSkuInit(storeId, detailRespose,cateStorePath.toString(),goods.getId());

        // 发送删除es商品的信息
        List<String> goodIds = new ArrayList<>();
        goodIds.add(goods.getId());
        applicationEventPublisher.publishEvent(TransactionCommitSendMQEvent
                .builder()
                .source("商品删除")
                .exchange(amqpExchangeProperties.getGoods())
                .routingKey(GoodsRoutingKey.GOODS_DELETE)
                .message(goodIds)
                .build());
    }

    /**
     * 初始化商品SKU并入库
     *
     * @param storeId       店铺ID
     * @param detailRespose 查询条件
     */
    public void goodsSkuInit(String storeId, DetailRespose detailRespose, String catePath,String goodsId) {
        for (DetailRespose.Specs specs : detailRespose.getSpecs()) {
            LambdaQueryWrapper<GoodsSku> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(GoodsSku::getStoreId,storeId);
            queryWrapper.eq(GoodsSku::getThirdPartyPlatformId,specs.getSpec_id());
            queryWrapper.last("limit 1");
            GoodsSku tempGoodsSku = goodsSkuService.getBaseMapper().selectOne(queryWrapper);

            GoodsSku goodsSku = new GoodsSku();
            goodsSku.setBig(detailRespose.getGoods().getDefault_image());
            goodsSku.setSmall(detailRespose.getGoods().getDefault_image());
            goodsSku.setBuyCount(0);
            //goodsSku.setCategoryPath(catePath);
            goodsSku.setCommentNum(0);
            goodsSku.setGoodsId(goodsId);
            goodsSku.setGoodsName("DD-" + detailRespose.getGoods().getGoods_name());
            goodsSku.setStoreId(storeId);
            goodsSku.setStoreName("供应");
            goodsSku.setSn(UuidUtils.getUUID());

            JSONObject url = new JSONObject();
            url.put("url",detailRespose.getGoods().getDefault_image());
            JSONArray images = new JSONArray();
            images.add(url);
            JSONObject json = new JSONObject();
            json.put("images",images);
            json.put("规格",StringUtils.isNotEmpty(specs.getSpec_name())?specs.getSpec_name():"默认");

            goodsSku.setSimpleSpecs(specs.getSpec_name());
            goodsSku.setSpecs(json.toJSONString());
            goodsSku.setGoodsType("PHYSICAL_GOODS");
            goodsSku.setIsGreenGoods(false);
            goodsSku.setQuantity(Integer.parseInt(specs.getStock()));
            goodsSku.setWeight(CurrencyUtil.convertDouble(detailRespose.getGoods().getVolume()));
            goodsSku.setCost(CurrencyUtil.reversalFen(CurrencyUtil.convertDouble(specs.getPrice())));
            goodsSku.setPrice(CurrencyUtil.mul(CurrencyUtil.reversalFen(CurrencyUtil.convertDouble(specs.getPrice())),1.05,1));
            goodsSku.setGreenScore(CurrencyUtil.mul(goodsSku.getCost(),0.1,0));
            goodsSku.setIsProxyGoods(true);
            goodsSku.setScene("STORE");
            goodsSku.setFreightTemplateId("0");
            goodsSku.setGrade(100D);
            goodsSku.setMarketEnable("DOWN");
            goodsSku.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name());
            goodsSku.setRecommend(true);
            goodsSku.setSalesModel("RETAIL");
            goodsSku.setSelfOperated(false);
            goodsSku.setTemplateId("0");
            goodsSku.setOriginal(detailRespose.getGoods().getDefault_image());
            goodsSku.setThumbnail(detailRespose.getGoods().getDefault_image());
            goodsSku.setIsProxyGoods(false);
            goodsSku.setSupportProxy(true);
            goodsSku.setSupportPurchase(true);
            goodsSku.setThirdPartyPlatformId(specs.getSpec_id());
            goodsSku.setThirdPartyPlatformType(2);
            goodsSku.setExtendId(storeId);
            goodsSku.setStoreCategoryPath(catePath);
            goodsSku.setGoodsUnit("件");
            goodsSku.setIntro(detailRespose.getGoods().getDescription());
            goodsSku.setMobileIntro(detailRespose.getGoods().getDescription());

            //插入商品sku
            if(tempGoodsSku == null){
                goodsSku.setCategoryPath("1,1,1");
                goodsSkuService.save(goodsSku);;
            }else{
                goodsSku.setId(tempGoodsSku.getId());
                BeanUtils.copyProperties(goodsSku,tempGoodsSku);
                goodsSkuService.update(tempGoodsSku);
            }
        }
    }
}
